<template>
  <div class="app-container">
    <br>
    <br>
    <el-form :model="query" ref="query" label-width="68px">
      <el-row :gutter=10>
        <el-col :span = 4 >
          <el-form-item label="一级类型" prop="firstType">
            <el-select v-model="query.firstType" placeholder="请选择">
              <el-option
                v-for="item in queryFirstTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="changeQueryDrugType(item, 1)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span = 4 :offset=2>
          <el-form-item label="二级类型" prop="secondType">
            <el-select v-model="query.secondType" placeholder="请选择">
              <el-option
                v-for="item in querySecondTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="changeQueryDrugType(item, 2)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span = 4 :offset=2>
          <el-form-item label="三级类型" prop="thirdType">
            <el-select v-model="query.thirdType" placeholder="请选择" @change="search">
              <el-option
                v-for="item in queryThirdTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter=10>
        <el-col :span=8>
          <el-form-item label="名称" prop="pinyinCode" >
              <el-input v-model="query.pinyinCode" placeholder="请输入商品名/通用名"/>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="search" >搜索</el-button>
            <el-button @click="resetForm('query')">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button type="primary" @click="add">新增药品</el-button>
    <br>
    <br>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="编码" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.code }}
        </template>
      </el-table-column>
      <el-table-column label="商品" width="400" align="center">
        <template slot-scope="scope">
          {{ '(' + scope.row.commonName + ')' }}
          {{ scope.row.name }}
          {{ '('+ scope.row.specs + ')' }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="通用名" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.commonName }}
        </template>
      </el-table-column> -->
      <el-table-column label="类型" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.firstTypeName + ' / ' + scope.row.secondTypeName + ' / ' + scope.row.thirdTypeName }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="管理部门" width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.deptName }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="厂家" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.factory }}
        </template>
      </el-table-column> -->
      <el-table-column label="剂型" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.form }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="规格" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.specs }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="销售权限" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.sellJobDutyList }}
        </template>
      </el-table-column> -->
      <el-table-column label="销售方式" width="80" align="center">
        <template slot-scope="scope">
          {{ scope.row.sellMethod | sellMethodFilter }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="标签" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.tagId }}
        </template>
      </el-table-column> -->
      <el-table-column label="厂家" width="180" align="center">
        <template slot-scope="scope">
          {{ scope.row.factoryName }}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="140" align="center">
        <template slot-scope="scope">
          <el-dropdown size="mini" trigger="click" @command="updateStatus" >
            <el-button size="mini" :type="scope.row.status | statusColorFilter" :loading="statusLoading">
              {{ scope.row.status | statusNameFilter }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="composeValue(scope.row, 1)">上架</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 0)">下架</el-dropdown-item>
              <el-dropdown-item :command="composeValue(scope.row, 2)">售罄下架</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-tag :type="scope.row.status | statusColorFilter">{{ scope.row.status | statusNameFilter }}</el-tag> -->
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" align="center" width="300" >
        <template slot-scope="scope">
          <el-button type="primary"  @click="getInfo(scope.row)" size="small">详情</el-button>
          <el-button type="success"  @click="update(scope.row)" size="small">修改</el-button>
          <el-button type="info"  @click="toCopy(scope.row)" size="small">复制</el-button>
          <el-button type="danger" @click="deleteInfo(scope)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="->, total, prev, pager, next"
      :total="this.total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="clickCurPage"
      >
    </el-pagination>
  <el-dialog title="物品详情" :visible.sync="infoVisible" width="1300px">
    <h2>基本信息</h2>
    <el-form ref="info" :model="info" label-width="80px">
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="一级类别">
            <el-select style="width: 100%" v-model="info.firstType" placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in firstTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="二级类别">
            <el-select style="width: 100%" v-model="info.secondType" placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in secondTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="三级类别">
            <el-select style="width: 100%" v-model="info.thirdType" placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in thirdTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="物品编码">
              <el-input v-model="info.code" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="通用名">
              <el-input v-model="info.commonName" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="药品名">
              <el-input v-model="info.name" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="拼音简码">
              <el-input v-model="info.pinyinCode" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="生产厂家">
            <el-select v-model="info.factory" placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in factoryEnum"
                :key="item.id"
                :label="item.factory"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="管理部门" prop="dept">
            <el-select style="width: 100%" v-model="info.deptId" placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in deptEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="规格" >
              <el-input v-model="info.specs" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="剂型">
            <el-select v-model="info.form" placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in formEnum"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=6 >
          <el-form-item label="剂量/单位">
            <el-input v-model="info.innerContentNumber" style="width: 180px" :disabled="true">
              <el-select v-model="info.innerContentUnit" slot="append" placeholder="请选择" style="width: 80px" :disabled="true">
                <el-option
                  v-for="item in unitEnum"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span=6 >
          <el-form-item label="制剂数量/单位" label-width="120px">
            <el-input v-model="info.innerNum" style="width: 180px;"  :disabled="true">
              <el-select v-model="info.innerUnit" slot="append" placeholder="请选择" style="width: 80px" :disabled="true">
                <el-option
                  v-for="item in contentUnitEnum"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span=6 >
          <el-form-item label="外包装单位" label-width="100px">
            <el-select v-model="info.outerUnit" placeholder="请选择" style="width: 80px" :disabled="true">
              <el-option
                v-for="item in unitEnum"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=6 >
          <el-form-item label="打包数量/单位" label-width="120px">
            <el-input v-model="info.outerContentNumber" style="width: 150px;"  :disabled="true">
              <el-select v-model="info.outerContentUnit" slot="append" placeholder="请选择" style="width: 65px" :disabled="true">
                <el-option
                  v-for="item in unitEnum"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="销售权限">
            <el-select style="width: 100%;" v-model="info.sellJobDutyList" multiple placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in JobDutyEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="销售方式">
            <el-select style="width: 100%;" v-model="info.sellMethod" placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in sellMethodEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="售价">
            <el-input type="Number" min=0 v-model="info.unitPrice" :disabled="true">
              <span slot="append">元/{{info.sellMethod===1? info.outerUnit : info.innerUnit}}</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="采购周期">
              <el-input type="Number" min=0 v-model="info.buyCycle" :disabled="true">
              <span slot="append">天</span>
              </el-input>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="最低采购" >
              <el-input type="Number" min=0 v-model="info.minPurchaseNum" :disabled="true">
              </el-input>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="预警数量">
            <el-input type="Number" min=0 v-model="info.warnNum" :disabled="true">
              <span slot="append">{{info.outerUnit}}</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span= 24 >
          <el-form-item label="描述">
              <el-input v-model="info.description" type="textarea" :autosize="{ minRows: 3, maxRows: 4}" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span= 24>
          <el-form-item label="标签" >
            <el-select style="width: 100%;" v-model="info.tag" multiple placeholder="请选择" :disabled="true" >
              <el-option
                v-for="item in tagEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 检查项 -->
      <el-row v-if="form.firstType == 32">
        <el-col :span= 8>
          <el-form-item label="报告模板" label-width="120px" prop="checkTemplate">
            <el-select style="width: 100%;" v-model="info.checkTemplate" placeholder="请选择" :disabled="true">
              <el-option
                v-for="item in checkTemplateEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span= 4>
          <el-form-item label="是否入库" label-width="100px">
            <el-radio-group v-model="form.story">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span= 6 v-if="!info.story || info.story == false">
          <el-form-item label="成本价" prop="costPrice">
              <el-input type="Number" min=0 v-model="info.costPrice" :disabled="true">
                <span slot="append">元</span>
              </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row v-if="form.firstType == 32">
        <el-col :span= 8>
          <el-form-item label="结果时长" label-width="80px" prop="resultTime">
            <el-select style="width: 100%;" v-model="form.resultTime" placeholder="请选择" >
              <el-option
                v-for="item in resultTimeEnum"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span= 6 v-if="form.resultTime == '小时'">
          <el-form-item prop="timeNumber">
            <el-input type="Number" min=0 v-model="form.timeNumber" >
              <span slot="append">小时</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="药品图片" prop="code">
              <img v-if="this.info.pic" :src="this.info.pic" alt="Uploaded Image" style="width: 200px;height: 200px"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog :title="dialogTitle" :visible.sync="formVisible" width="1300px" :close-on-click-modal="false" >
    <h2>基本信息</h2>
    <el-form ref="form" :model="form" label-width="80px" :rules="formRules">
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="物品编码" prop="code">
              <el-input v-model="form.code" :disabled="true"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="一级类别" prop="firstType">
            <el-select style="width: 100%" v-model="form.firstType" placeholder="请选择">
              <el-option
                v-for="item in firstTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="changeDrugType(item.id, item.abb, 1)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="二级类别" prop="secondType">
            <el-select style="width: 100%" v-model="form.secondType" placeholder="请选择">
              <el-option
                v-for="item in secondTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="changeDrugType(item.id, item.abb, 2)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="三级类别" prop="thirdType">
            <el-select style="width: 100%" v-model="form.thirdType" placeholder="请选择" @change="$forceUpdate()">
              <el-option
                v-for="item in thirdTypeEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="changeDrugType(item.id, item.abb, 3)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="通用名" prop="commonName">
            <el-autocomplete
              class="inline-input"
              v-model="form.commonName"
              :fetch-suggestions="queryCommonSearch"
              placeholder="请输入通用名"
              @select="inputName1"
              @input="inputName1"
            ></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="药品名" prop="name">
            <el-autocomplete
              class="inline-input"
              v-model="form.name"
              :fetch-suggestions="queryNameSearch"
              placeholder="请输入药品名"
              @select="inputName1"
              @input="inputName1"
            ></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="拼音简码" prop="pinyinCode">
              <el-input v-model="form.pinyinCode" :disabled="true"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="生产厂家" prop="factory">
            <el-select v-model="form.factory" filterable placeholder="请选择" >
              <el-option
                v-for="item in factoryEnum"
                :key="item.id"
                :label="item.factory"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="管理部门" prop="dept">
            <el-select style="width: 100%" v-model="form.deptId" placeholder="请选择" >
              <el-option
                v-for="item in deptEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="规格" prop="specs">
              <el-input v-model="form.specs" :disabled="true"/>
          </el-form-item>
        </el-col>
        <el-col :span=8 >
          <el-form-item label="剂型" :prop="form.firstType == 1 || ''+form.firstType+form.secondType == '716' ? 'form' : ''">
            <el-select v-model="form.form" placeholder="请选择">
              <el-option
                v-for="item in formEnum"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <br>
            <span style="color: red;">例: 50ml*30片*盒</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=6 >
          <el-form-item label="剂量/单位" label-width="100px" prop="innerContent">
            <el-input type="number" :min="form.minNumber" v-model="form.innerContentNumber" style="width: 180px" @input="buildSpecs" >
              <el-select v-model="form.innerContentUnit" slot="append" placeholder="请选择" style="width: 80px" @change="buildSpecs" >
                <el-option
                  v-for="item in unitEnum"
                  :key="item"
                  :label="item"
                  :value="item"
                  @click.native="buildSpecs"
                  >
                </el-option>
              </el-select>
            </el-input>
            <br>
            <span style="color: red;">例: 50ml</span>
          </el-form-item>
        </el-col>
        <el-col :span=6 >
          <el-form-item label="制剂数量/单位" label-width="120px" prop="innerNum">
            <el-input type="number" min=0 v-model="form.innerNum" style="width: 180px;"  @input="buildSpecs">
              <el-select v-model="form.innerUnit" slot="append" placeholder="请选择" style="width: 80px" @change="buildSpecs">
                <el-option
                  v-for="item in contentUnitEnum"
                  :key="item"
                  :label="item"
                  :value="item"
                  @click.native="buildSpecs"
                  >
                </el-option>
              </el-select>
            </el-input>
            <br>
            <span style="color: red;">例: 30片</span>
          </el-form-item>
        </el-col>
        <el-col :span=6 >
          <el-form-item label="外包装单位" label-width="120px" prop="outerUnit">
            <el-select v-model="form.outerUnit" placeholder="请选择" style="width: 80px"  @change="buildSpecs">
              <el-option
                v-for="item in unitEnum"
                :key="item"
                :label="item"
                :value="item"
                @click.native="buildSpecs"
                >
              </el-option>
            </el-select>
            <br>
            <span style="color: red;">例: 盒</span>
          </el-form-item>
        </el-col>
        <el-col :span=6 >
          <el-form-item label="打包数量/单位" label-width="120px" >
            <el-input v-model="form.outerContentNumber" style="width: 150px;">
              <el-select v-model="form.outerContentUnit" slot="append" placeholder="请选择" style="width: 65px">
                <el-option
                  v-for="item in unitEnum"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="销售权限">
            <el-select style="width: 100%;" v-model="form.sellJobDutyList" multiple placeholder="请选择">
              <el-option
                v-for="item in JobDutyEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="销售方式" prop="sellMethod">
            <el-select style="width: 100%;" v-model="form.sellMethod" placeholder="请选择">
              <el-option
                v-for="item in sellMethodEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="售价" prop="unitPrice">
            <el-input type="Number" min=0 v-model="form.unitPrice" >
              <span slot="append">元/{{form.sellMethod===1? form.outerUnit : form.innerUnit}}</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=8>
          <el-form-item label="采购周期">
              <el-input type="Number" min=0 v-model="form.buyCycle" >
              <span slot="append">天</span>
              </el-input>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="最低采购" >
              <el-input type="Number" min=0 v-model="form.minPurchaseNum" >
              </el-input>
          </el-form-item>
        </el-col>
        <el-col :span=8>
          <el-form-item label="预警数量">
            <el-input type="Number" min=0 v-model="form.warnNum" >
              <span slot="append">{{form.outerUnit}}</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span= 24 >
          <el-form-item label="描述">
            <el-input v-model="form.description" type="textarea" :autosize="{ minRows: 3, maxRows: 4}" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span= 24>
          <el-form-item label="标签" >
            <el-select style="width: 100%;" v-model="form.tag" multiple placeholder="请选择" >
              <el-option
                v-for="item in tagEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 检查项 -->
      <el-row v-if="form.firstType == 32">
        <el-col :span= 8>
          <el-form-item label="报告模板" prop="checkTemplate">
            <el-select style="width: 100%;" v-model="form.checkTemplate" placeholder="请选择" >
              <el-option
                v-for="item in checkTemplateEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span= 4>
          <el-form-item label="是否入库" label-width="100px">
            <el-radio-group v-model="form.story">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span= 6 v-if="!form.story || form.story == false">
          <el-form-item label="成本价" prop="costPrice">
              <el-input type="Number" min=0 v-model="form.costPrice" >
                <span slot="append">元</span>
              </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="form.firstType == 32">
        <el-col :span= 8>
          <el-form-item label="结果时长" label-width="80px" prop="resultTime">
            <el-select style="width: 100%;" v-model="form.resultTime" placeholder="请选择" >
              <el-option
                v-for="item in resultTimeEnum"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span= 6 v-if="form.resultTime == '小时'">
          <el-form-item prop="timeNumber">
            <el-input type="Number" min=0 v-model="form.timeNumber" >
              <span slot="append">小时</span>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
     
      <el-row :gutter="10">
        <el-col :span=8 >
          <el-form-item label="药品图片" prop="code">
              <input type="file" @change="convertToBase64" />
              <div style="width: 200px;height: 200px;padding: 5px">
                <img v-if="form.pic" :src="form.pic"  style="width: 195px;height: 195px;"/>  
                <i v-if="form.pic && form.pic != ''" @click="remove_img" class="clear"><span style="position: absolute; top: -8px;right: 8px">X</span></i>
              </div>
          </el-form-item>
        </el-col>
      </el-row>
        
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm">确 定</el-button>
        <div style="width:200px;display: inline-block;"> </div>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  </div>
</template>

<script>
import { getList, getDrugCode, add, edit, editPic, del, getPic } from '@/api/drug'
import { getList as getTagList } from '@/api/tag'
import { getList as getJobDutyList } from '@/api/jobDuty'
import { getTreeList as getDugTypeTreeList } from '@/api/drugType'
import { getList as getDictionaryList } from '@/api/dictionary'
import { getList as getFactoryList } from '@/api/factory'
import { getList as getDeptList } from '@/api/dept'
import { pinyin } from 'pinyin-pro'

export default {
  name: "DrugList",
  filters: {
    statusColorFilter(status) {
      const statusMap = ['danger', 'primary', 'warning']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['下架', '上架', '售罄下架']
      return statusMap[status]
    },
    sellMethodFilter(status) {
      const statusMap = ['', '整装', '分装', '整装/分装']
      return statusMap[status]
    }

  },
  data() {
    const validateType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型')) 
      else callback()
    }
    const validateCommonName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请填写通用名'))
      }
      else {
        callback()
      }
    }
    const validateName = (rule, value, callback) => {
      if (!value) callback(new Error('请填写名称'))
      else callback()
    }
    const validatePinyinCode = (rule, value, callback) => {
      if (!value) callback(new Error('请填写拼音简码'))
      else callback()
    }
    const validateFactory = (rule, value, callback) => {
      if (!this.form.factory ) callback(new Error('请填写厂家'))
      else callback()
    }
    const validateSpecs = (rule, value, callback) => {
      if (!value) callback(new Error('请填写规格'))
      else callback()
    }
    const validateInnerContent = (rule, value, callback) => {
      if (!this.form.innerContentNumber && this.form.innerContentNumber != 0) callback(new Error('请填写剂量/单位'))
      else callback()
    }
    const validateInnerNum = (rule, value, callback) => {
      if (!this.form.innerNum && this.form.innerNum != 0) callback(new Error('请填写制剂数量/单位'))
      else callback()
    }
    const validateOuterContent = (rule, value, callback) => {
      if (!this.form.outerContentNumber ) callback(new Error('请填写外包装/单位'))
      else callback()
    }
    const validateDept = (rule, value, callback) => {
      if (!this.form.deptId ) callback(new Error('请选择管理部门'))
      else callback()
    }
    const validateForm = (rule, value, callback) => {
      if (!this.form.form ) callback(new Error('请选择剂型'))
      else callback()
    }
    const validateOuterUnit = (rule, value, callback) => {
      if (!this.form.outerUnit ) callback(new Error('请选择外包装单位'))
      else callback()
    }
    const validateUnitPrice = (rule, value, callback) => {
      if (!this.form.unitPrice && this.form.unitPrice != 0) callback(new Error('请填写售价'))
      else callback()
    }
    const validateCheckTemplate = (rule, value, callback) => {
      if (!this.form.checkTemplate ) callback(new Error('请选择检查模板'))
      else callback()
    }
    const validateCostPrice = (rule, value, callback) => {
      if (!this.form.costPrice ) callback(new Error('请填写成本价'))
      else callback()
    }
    const validateSellMethod = (rule, value, callback) => {
      if (!this.form.sellMethod ) callback(new Error('请选择销售方式'))
      else callback()
    }
    const validateResultTime = (rule, value, callback) => {
      if (!this.form.resultTime ) callback(new Error('请输入选择结果时长'))
      else callback()
    }
    const validateTimeNumber = (rule, value, callback) => {
      if (!this.form.timeNumber ) callback(new Error('请输入结果时间'))
      else callback()
    }
    return {
      list: null,
      listLoading: true,
      statusLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      dialogTitle: '',
      info: {},
      form: {},
      firstTypeEnum: [],
      secondTypeEnum: [],
      thirdTypeEnum: [],
      queryFirstTypeEnum: [],
      querySecondTypeEnum: [],
      queryThirdTypeEnum: [],
      stores:[],
      JobDutyEnum:[],
      sellMethodEnum:[{id: 1, name: '整装'}, {id: 2, name: '分装'}],
      unitEnum: [],
      contentUnitEnum: [],
      formEnum: [],
      factoryEnum: [],
      deptEnum: [],
      stores:[],
      query: {},
      tagEnum: [],
      tmpTag: {},
      dugTypeTreeList: [],
      formRules: {
        firstType: [{ required: true, trigger: 'blur', validator: validateType }],
        secondType: [{ required: true, trigger: 'blur', validator: validateType }],
        thirdType: [{ required: true, trigger: 'blur', validator: validateType }],
        commonName: [{ required: true, trigger: 'blur', validator: validateCommonName }],
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        pinyinCode: [{ required: true, trigger: 'blur', validator: validatePinyinCode }],
        factory: [{ required: true, trigger: 'blur', validator: validateFactory }],
        specs: [{ required: true, trigger: 'blur', validator: validateSpecs }],
        innerContent: [{ required: true, trigger: 'blur', validator: validateInnerContent }],
        innerNum: [{ required: true, trigger: 'blur', validator: validateInnerNum }],
        outerContent: [{ required: true, trigger: 'blur', validator: validateOuterContent }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
        form: [{ required: true, trigger: 'blur', validator: validateForm }],
        outerUnit: [{ required: true, trigger: 'blur', validator: validateOuterUnit }],
        unitPrice: [{ required: true, trigger: 'blur', validator: validateUnitPrice }],
        checkTemplate: [{ required: true, trigger: 'blur', validator: validateCheckTemplate }],
        costPrice: [{ required: true, trigger: 'blur', validator: validateCostPrice }],
        sellMethod: [{ required: true, trigger: 'blur', validator: validateSellMethod }],
        resultTime: [{ required: true, trigger: 'blur', validator: validateResultTime }],
        timeNumber: [{ required: true, trigger: 'blur', validator: validateTimeNumber }],
      },
      checkTemplateEnum: [
        {id: 1, name: '血常规模板'},
        {id: 2, name: '尿常规模板'},
      ],
      resultTimeEnum: ["即刻", "次日", "小时"],
      allDrugEnum: [],
      allDrugCommonName: [],
      allDrugName: [],
    }
    
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize
      }
      getList(reqBody).then(response => {
        console.log(response)
        this.list = response.data.records
        this.list.forEach(drug=>{
          drug.tag = drug.tagList
          // drug.deptId = drug.drugDeptIds[0]
        })
        this.total = response.data.total
        this.listLoading = false
      })
      getJobDutyList().then(jobDutyRes=>{
        this.JobDutyEnum = jobDutyRes.data
      })
      getDugTypeTreeList().then(drugTypeTreeList=> {
        this.drugTypeTreeList = drugTypeTreeList.data
        this.queryFirstTypeEnum = JSON.parse(JSON.stringify(this.drugTypeTreeList))
      })
      getDictionaryList({type: 0}).then(dictionaryRes => {
        console.log(dictionaryRes.data)
        this.formEnum = dictionaryRes.data.map(item => item.name)
      })
      getDictionaryList({type: 1}).then(dictionaryRes => {
        console.log(dictionaryRes.data)
        this.unitEnum = dictionaryRes.data.map(item => item.name)
        this.unitEnum.unshift('无')
        this.contentUnitEnum = JSON.parse(JSON.stringify(this.unitEnum))
      })
      getTagList().then(tagRes=>{
        this.tagEnum = tagRes.data
      })
      getFactoryList().then(factoryRes=>{
        console.log(factoryRes)
        this.factoryEnum = factoryRes.data
      })
      getDeptList().then(deptRes=>{
        this.deptEnum = deptRes.data
      })
      getList({currentPage: 1, pageSize: 9999}).then(res=> {
        this.allDrugEnum = res.data.records
        for (const drug of this.allDrugEnum) {
          if(!this.allDrugCommonName.map(item=>item.value).includes(drug.commonName)) {
            this.allDrugCommonName.push({value: drug.commonName})
          }
          if(!this.allDrugName.map(item=>item.value).includes(drug.name)) {
            this.allDrugName.push({value: drug.name})
          }
        }
      })
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    add() {
      this.reset()
      this.dialogTitle = '新增药品'
      this.$set(this, 'firstTypeEnum', JSON.parse(JSON.stringify(this.queryFirstTypeEnum)))
      this.form.code = '---'+'------'
      this.$set(this.form, 'commonName', '')
      this.$set(this.form, 'name', '')
      this.$set(this.form, 'innerContentNumber', '')
      this.$set(this.form, 'innerContentUnit', '')
      this.$set(this.form, 'innerNum', '')
      this.$set(this.form, 'innerUnit', '')
      this.$set(this.form, 'outerUnit', '')
      this.$set(this.form, 'minNumber', 0)
      this.formVisible = true
    },
    getInfo(row) {
      this.info = row
      this.$set(this, 'firstTypeEnum', JSON.parse(JSON.stringify(this.drugTypeTreeList)))
      this.$set(this, 'secondTypeEnum', this.getChildList(this.info.firstType))
      this.$set(this, 'thirdTypeEnum', this.getChildList(this.info.secondType))
      getPic(this.info.id).then(res=> {
        this.info.pic = res.data.picture
        this.infoVisible = true
      })
    },
    update(row) {
      this.reset()
      this.dialogTitle = '修改药品'
      this.form = JSON.parse(JSON.stringify(row))
      this.$set(this, 'firstTypeEnum', JSON.parse(JSON.stringify(this.drugTypeTreeList)))
      this.$set(this, 'secondTypeEnum', this.getChildList(this.form.firstType))
      this.$set(this, 'thirdTypeEnum', this.getChildList(this.form.secondType))
      this.$set(this.form, 'minNumber', 0)
      getPic(this.form.id).then(res=> {
        this.$set(this.form, 'pic', res.data.picture)
        this.formVisible = true
        console.log(this.form)
      })
    },
    deleteInfo(scope) {
      console.log(scope.row)
      this.$confirm('确定删除该职务?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(scope.row.id).then(res=>{
          this.list.splice(scope.$index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(err=>{
          console.log(err)
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    confirm() {
      console.log(this.form)
      this.$refs.form.validate(valid => {
        if (valid) {
          this.listLoading = true
          this.form.drugDeptIds = [this.form.deptId]
          if(this.form.id) {  // update
            edit(this.form).then(res=>{
              console.log(res)
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.formVisible = false
              getList({currentPage: this.currentPage,pageSize: this.pageSize}).then(response => {
                console.log(response)
                this.list = response.data.records
                this.list.forEach(drug=>{
                  drug.tag = drug.tagList
                  // drug.deptId = drug.drugDeptIds[0]
                })
                this.total = response.data.total
                this.listLoading = false
              })
            }).catch(err=>{
              console.log(err)
            })
          } else { // add
            add(this.form).then(res=>{
              this.formVisible = false
              this.listLoading = false
              this.$tab.refreshPage({path: '/store/list', name: "DrugList"});
            }).catch(err=>{
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      this.infoVisible = false
      this.formVisible = false
    },
    reset(){
      this.form = {}
    },
    buildSpecs() {
      var specsOne = (this.form.innerContentNumber?this.form.innerContentNumber:'') + (this.form.innerContentUnit?this.form.innerContentUnit:'') + '*'
      var specsTwo = this.form.innerNum == 0 && this.form.innerUnit == '无' ? '' : (this.form.innerNum?this.form.innerNum:'') + (this.form.innerUnit?this.form.innerUnit:'') + '*'
      var specsThree = this.form.outerUnit
      if(this.form.firstType != 1 && ''+this.form.firstType+this.form.secondType != '716') {
        specsOne = this.form.innerContentNumber == 0 && this.form.innerContentUnit == '无' ? '' : (this.form.innerContentNumber?this.form.innerContentNumber:'') + (this.form.innerContentUnit?this.form.innerContentUnit:'') + '*'
      }
      this.form.specs = specsOne + specsTwo + specsThree
    },
    selectTagId(item) {
      this.form.tagId.push(item)
    },
    changeDrugType(id, abb, level) {
      var code = JSON.parse(JSON.stringify(this.form.code));
      if(level === 1) {
        this.form.secondType = undefined
        this.form.thirdType = undefined
        this.$set(this, 'secondTypeEnum', this.getChildList(id))
        this.thirdTypeEnum = []
      } else if (level === 2) {
        this.form.thirdType = undefined
        this.$set(this, 'thirdTypeEnum', this.getChildList(id))
      } 
      this.$delete(this.form, 'code')
      this.$set(this.form, 'code', code.substr(0,1) + code.substr(1,2) + code.substr(2,3))
      if(this.form.firstType && this.form.secondType && this.form.thirdType) {
        getDrugCode({firstType: this.form.firstType, secondType: this.form.secondType, thirdType: this.form.thirdType}).then(res=> {
          code = res.data
          this.$delete(this.form, 'code')
          this.$set(this.form, 'code', code)
        })
      }
      if(!this.unitEnum.includes('无')) this.unitEnum.unshift('无')
      if(!this.contentUnitEnum.includes('无')) this.contentUnitEnum.unshift('无')
      this.form.minNumber = 0
      if (this.form.firstType == 1 || ''+this.form.firstType+this.form.secondType == '716' ) {
        this.unitEnum = this.unitEnum.filter(item => item != '无')
        this.$set(this.form, 'minNumber', 1)
        if(this.form.innerContentNumber == 0) this.form.innerContentNumber = undefined
        if(this.form.innerContentUnit == '无') this.form.innerContentUnit = undefined
        // if(this.form.innerNumber == 0) this.form.innerNumber = undefined
        // if(this.form.innerUnit == '无') this.form.innerUnit = undefined
      }
    },
    changeQueryDrugType(item, level) {
      if(level == 1) {
        this.query.secondType = undefined
        this.query.thirdType = undefined
        this.$set(this, 'querySecondTypeEnum', this.getChildList(item.id))
        this.queryThirdTypeEnum = []
      } else if (level == 2) {
        this.query.thirdType = undefined
        this.$set(this, 'queryThirdTypeEnum', this.getChildList(item.id))
      }
    },
    getChildList(id) {
      const node = this.getNode(id, this.drugTypeTreeList)
      if(node.children && node.children.length>0) return node.children
      else return []
    },
    getNode(id, arr) {
      for (const first of arr) {
        if(first.id === id) return first;
        if(first.children && first.children.length > 0) {
          for (const second of first.children) {
            if(second.id === id) return second;
            if(second.children && second.children.length > 0) {
              for (const third of second.children) {
                if(third.id === id) return third;
              }
            }
          }
        }
      }
    },
    search() {
      this.listLoading = true
      this.query.currentPage = 1
      this.query.pageSize = this.pageSize
      getList(this.query).then(response => {
        this.list = response.data.records
        this.list.forEach(drug=>{
          drug.tag = drug.tagList
          // drug.deptId = drug.drugDeptIds[0]
        })
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    toCopy(row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.form.id = undefined
      this.$set(this, 'firstTypeEnum', JSON.parse(JSON.stringify(this.drugTypeTreeList)))
      this.$set(this, 'secondTypeEnum', this.getChildList(this.form.firstType))
      this.$set(this, 'thirdTypeEnum', this.getChildList(this.form.secondType))
      this.formVisible = true
    },
    inputName1() {
      var allName = this.form.commonName.concat(this.form.name)
      console.log(allName)
      var pinyinCode = pinyin(allName, {
        pattern: 'first',
        toneType: 'none',
      }).replaceAll(' ','')
      this.form.pinyinCode = pinyinCode
    },
    composeValue(row, status) {
      return {
        row,
        status
      }
    },
    updateStatus(value) {
      this.statusLoading = true
      value.row.status = value.status
      edit(value.row).then(res=> {
        console.log(res)
        this.$message.success("修改状态成功")
        this.statusLoading = false
      })
    },
    convertToBase64(event) {
      const file = event.target.files[0];
      if (file) {
        this.$set(this.form, 'pic', undefined)
        const reader = new FileReader();
        reader.onload = (e) => {
          this.$set(this.form, 'pic', e.target.result)
        };
        reader.readAsDataURL(file);
      }
    },
    remove_img() {
      this.$set(this.form, 'pic', undefined)
    },
    queryCommonSearch(queryString, cb) {
      var restaurants = this.allDrugCommonName;
        var results = queryString ? restaurants.filter(item => item.value.includes(queryString)) : restaurants;
      cb(results);
    },
    queryNameSearch(queryString, cb) {
      var restaurants = this.allDrugName;
        var results = queryString ? restaurants.filter(item => item.value.includes(queryString)) : restaurants;
      cb(results);
    },
  }
}

</script>

<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .clear {
    position: absolute;
    top: 12px;
    right: 12px;
    height: 24px;
    width: 24px;
    border-radius: 50%;
    background-color: #d7d7d7;
  }
</style>